import Vue from 'vue';
import VueRouter from 'vue-router';
import { Toast } from 'vant';
// import Home from '@/views/home/home.vue';

// import * as ClientJSAPIHelpers from '@/helpers/client-jsapi';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Home',
    // component: Home,
    component: () => import(/* webpackChunkName: "home" */ '@/views/home/home.vue'),
  },
  {
    path: '/exam',
    name: 'Exam',
    component: () => import('@/views/exam/exam.vue'),
    meta: {
      title: '考试详情',
    },
  },
  {
    path: '/examing',
    name: 'Examing',
    component: () => import('@/views/examing/examing.vue'),
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '@/views/about/about.vue'),
  },
  {
    path: '/result',
    name: 'Result',
    component: () => import(/* webpackChunkName: "paging" */ '@/views/result/result.vue'),
  },
  {
    path: '/code-template/paging',
    name: 'Paging',
    component: () => import(/* webpackChunkName: "paging" */ '@/code-template/paging/paging.vue'),
  },
  {
    path: '*',
    name: '404',
    component: () => import(/* webpackChunkName: "404" */ '@/views/404/404.vue'),
  },
  {
    path: '/onlineWork',
    name: 'work',
    // component: Home,
    component: () => import(/* webpackChunkName: "work" */ '@/views/home/onlineWork.vue'),
    meta: {
      title: '作业',
    },
  },
  {
    path: '/survey',
    name: 'survey',
    // component: Home,
    component: () => import(/* webpackChunkName: "survey" */ '@/views/survey/survey.vue'),
    meta: {
      title: '问卷调查',
    },
  },
  {
    path: '/surveyList',
    name: 'surveyList',
    // component: Home,
    component: () => import(/* webpackChunkName: "survey" */ '@/views/survey/surveyList.vue'),
    meta: {
      title: '问卷调查',
    },
  },
  {
    path: '/work',
    name: 'work',
    // component: Home,
    component: () => import(/* webpackChunkName: "work" */ '@/views/work/index.vue'),
    meta: {
      name: 'work',
      title1: '作业',
      title2: '课堂训练',
    },
  },
];

const router = new VueRouter({
  routes,
});

// https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
router.beforeEach((to, from, next) => {
  const token = to.query.token ? to.query.token : '';
  const type = to.query.type;
  const sToken = sessionStorage.getItem('token');
  if (to.meta && to.meta.title) {
    if (to.meta.name == 'work') {
      document.title = to.meta['title' + type];
    } else {
      document.title = to.meta.title;
    }
  }

  if (to.name == '404') {
    next();
    return;
  }
  if (token && !sToken) {
    sessionStorage.setItem('token', token);
  }
  if (!sToken && !token) {
    Toast('获取用户信息失败，请重新打开');
    next('/404');
    return;
  }
  next();
});

export default router;
